package kayao.common;

public class NetworkUtils {
	// NOTE: You might find the implementations weird, but it's to reduce memory
	//       allocations on the phone, so please use them.
	public static void insertIntToByteArray(byte[] array, int index, int value) {
		array[index] = (byte)(value >> 24);
		array[index + 1] = (byte)((value << 8) >> 24);
		array[index + 2] = (byte)((value << 16) >> 24);
		array[index + 3] = (byte)((value << 24) >> 24);
	}
	
	public static int insertByteArrayToInt(byte[] array, int index) {
		int i = 0;
		i += unsignedByteToInt(array[index]) << 24;
		i += unsignedByteToInt(array[index + 1]) << 16;
		i += unsignedByteToInt(array[index + 2]) << 8;
		i += unsignedByteToInt(array[index + 3]) << 0;
		return i;
	}
	
	public static void insertFloatToByteArray(byte[] array, int index, float value) {
		insertIntToByteArray(array, index, Float.floatToRawIntBits(value));
	}
	
	public static float insertByteArrayToFloat(byte[] array, int index) {
		int i = 0;
		i += unsignedByteToInt(array[index]) << 24;
		i += unsignedByteToInt(array[index + 1]) << 16;
		i += unsignedByteToInt(array[index + 2]) << 8;
		i += unsignedByteToInt(array[index + 3]) << 0;
		return Float.intBitsToFloat(i);
	}
	
	public static void insertShortToByteArray(byte[] array, int index, short value) {
		array[index] = (byte)((value >> 8) & 0xFF);
		array[index + 1] = (byte)(value  & 0xFF);
	}
	
	public static short insertByteArrayToShort(byte[] array, int index) {
		short s = 0;
		s += unsignedByteToShort(array[index]) << 8;
		s += unsignedByteToShort(array[index + 1]) << 0;
		return s;
	}
	
	public static int unsignedByteToInt(byte b) {
		return (int)b & 0xFF;
	}
	
	public static int unsignedByteToShort(byte b) {
		return (short)b & 0xF;
	}
	/**
	 * It converts an int32 to a byte [2]
	 * @param i the integer
	 * @return the array [2]
	 */
	public static byte[] int32To2Bytes(int i) {
		short newv=(short)i;
		byte []bytes=new byte[2];
		bytes[0] =(byte)(( newv >> 8 ) & 0xFF);
		bytes[1] = (byte)( newv  & 0xFF);
		return bytes;
	}

	/**
	 * It converts an integer in an array[4] of bytes in C-2
	 * @param i
	 * @return
	 */
	public static byte[] int32ToByte(int i) 
	{
		byte []bytes=new byte[4];
		bytes[0] =(byte)( i >> 24 );
		bytes[1] =(byte)( (i << 8) >> 24 );
		bytes[2] =(byte)( (i << 16) >> 24 );
		bytes[3] =(byte)( (i << 24) >> 24 );
		return bytes;
	}
}
